# 骑手视图
from django.shortcuts import render,HttpResponse,redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from configuration.sms_code import send_message
import string
import random
from captcha.image import ImageCaptcha
import redis
import jwt
from rider.models import *
import time
from django.conf import settings
from configuration.jwt_decode import check_login
from django.core.paginator import Paginator
from configuration.redis_packaging import RedisPackaging
# Create your views here.


# 图片验证码的视图
class ImageCodeAPIView(APIView):
    def get(self, request, uuid):
        # 生成一个4位数随机码
        # string.ascii_letters：a-zA-Z所有字母
        # string.digits：数字0-9
        # random.sample：随机采样(返回列表类型)
        code = "".join(random.sample(string.ascii_letters + string.digits, 4))
        # 实例化一个图片验证码对象
        # 用captcha.image下的 ImageCaptcha 生成字符验证码图片
        img = ImageCaptcha()
        # 把这个验证码转换成图片形式的
        image_code = img.generate(code)  # 字节io对象
        # 验证码存入redis
        rds = RedisPackaging()
        rds.add(uuid,code)
        # 返回响应
        return HttpResponse(image_code, content_type="image/png")


# 获取验证码
class SmsView(APIView):
    def get(self,request,mobile):
        uuid = request.query_params.get('uuid')
        code = request.query_params.get('code')
        if not all([uuid,code]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })
        # 我去做个核酸，我在，
        print('>>>>>>>>>>',uuid,code)
        # 取出redis中uuid的值
        rds = RedisPackaging()
        code_r = rds.gain(uuid)
        print('>>>>>>>>>>>>>>',code_r)
        if not code_r:
            return Response({
                'code':400,
                'msg':'校验码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != code.lower():
            return Response({
                "code": 400,
                "msg": "校验码错误"
            })

        send_message(mobile)
        return Response({
            'code':200,
            'msg':'发送成功'
        })


# 手机验证码登入或注册
class UserView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        sms = request.data.get('sms')
        if not all([mobile,sms]):
            return Response({
                'code':400,
                'msg':'获取数据为空'
            })

        # 取出redis中uuid的值
        rds = RedisPackaging()
        key = 'sms_%s' % mobile
        code_r = rds.gain(key)
        if not code_r:
            return Response({
                'code': 400,
                'msg': '验证码已过期'
            })
        # 验证码还未过期，解码与前端对比
        if code_r.decode().lower() != sms.lower():
            return Response({
                "code": 400,
                "msg": "验证码错误"
            })

        # 判断此手机号是否注册
        user = RiderModel.objects.filter(mobile=mobile)
        if not user:
            # 没有注册，进行注册
            RiderModel.objects.create(
                mobile=mobile,
            )
        try:
            user = RiderModel.objects.get(mobile=mobile)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此信息'
            })

        token = jwt.encode({
            'uid':user.id,
            'username':user.r_name,
            'exp':time.time() + 720000
        },key=settings.SECRET_KEY,algorithm='HS256')

        return Response({
            'code':200,
            'msg':'登入成功',
            'token':token,
            'is_audit':user.is_audit,
            'cause_down':user.cause_down,
        })


# 骑手取餐
class QuCanView(APIView):
    @check_login
    def get(self, request):
        u_id = request.uid
        rider = RiderOrderModel.objects.filter(rider_id=u_id, status='1')
        rider_list = []
        for i in rider:
            rider_list.append({
                'order_id': i.order_id_id,
                'order': {
                    i.order_id.order_num,
                    i.order_id.amount,
                    i.order_id.establish_time,
                },
                'rider_id': i.rider_id,
                'status': i.status,
            })

        return Response({
            'code': 200,
            'msg': '获取成功',
            'data': rider_list
        })

    @check_login
    def post(self, request):
        u_id = request.uid
        r_id = request.data.get('r_id')

        # 修改状态
        try:
            rid = RiderOrderModel.objects.get(id=r_id)
        except Exception as e:
            return Response({
                'code': 400,
                'msg': '获取失败'
            })
        rid.status = '2'
        rid.save()

        return Response({
            'code': 200,
            'msg': '配送成功'
        })


# 获取所有付钱的订单供骑手抢夺
class OrderQView(APIView):
    def get(self,request):
        pay_order = PayOrderModel.objects.filter(status='1')
        pay_order_list = []
        for i in pay_order:
            pay_order_list.append({
                'id':i.id,
                'order_num':i.order_num,
                'uid':i.uid_id,
                'uid_name':{
                    'nickname':i.uid.c_name,
                    'portrait':i.uid.portrait,
                },
                'bid':i.bid_id,
                'bid_name':{
                    'nickname':i.bid.nickname,
                    'portrait':i.bid.portrait,
                },
                'fid':i.fid_id,
                'amount':i.amount,
                'status':i.status,
                'establish_time':i.establish_time,
                'change_time':datetime.strftime(i.change_time,'%Y-%m-%d %H:%M:%S'),
                'delete':i.delete,
            })
        return Response({
            'code':200,
            'msg':'获取成功',
            'data':pay_order_list
        })

    @check_login
    def post(self, request):
        u_id = request.uid
        order = request.data.get('order')
        print('>>>>>>>>',order,u_id)
        # 进行接单
        RiderOrderModel.objects.create(
            order_id_id=int(order),
            rider_id=u_id,
            status='0',
        )
        return Response({
            'code': 200,
            'msg': '抢单成功'
        })


# 骑手取单
class RiderOrderView(APIView):
    # 获取自己接受的订单
    @check_login
    def get(self,request):
        u_id = request.uid
        rider = RiderOrderModel.objects.filter(rider_id=u_id,status='0')
        rider_list = []
        for i in rider:
            rider_list.append({
                'order_id':i.order_id_id,
                'order':{
                    i.order_id.order_num,
                    i.order_id.amount,
                    i.order_id.establish_time,
                },
                'rider_id':i.rider_id,
                'status':i.status,
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':rider_list
        })

    @check_login
    def post(self,request):
        u_id = request.uid
        r_id = request.data.get('r_id')

        # 修改状态
        try:
            rid = RiderOrderModel.objects.get(id=r_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })
        rid.status = '1'
        rid.save()

        return Response({
            'code':200,
            'msg':'取单成功'
        })


# 完成订单
class AccomplishOrderView(APIView):
    @check_login
    def post(self,request):
        # 接受前端数据
        u_id = request.uid
        rider = request.data.get('rider')
        money = request.data.get('money')

        try:
            rider = RiderOrderModel.objects.get(id=rider)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取订单失败'
            })
        try:
            u_rider = RiderModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取用户失败'
            })

        rider.status = '1'
        u_rider.balance += float(money)
        rider.save()
        u_rider.save()

        return Response({
            'code':200,
            'msg':'完成订单'
        })


# 修改获取骑手信息
class Show_userInfo(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid
        try:
            users = RiderModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'没有此用户信息'
            })

        return Response({
            "code":200,
            "msg":"获取登录用户信息成功",
            "data":{
                "id": users.id,
                'r_name':users.r_name,
                'mobile':users.mobile,
                'password':users.password,
                'portrait':users.img,
                'login_time':users.login_time,
                'gender':users.gender,
                'reg_time':users.reg_time,
                'intro':users.intro,
                'status':users.status,
                'balance':users.balance,
                'freeze':users.freeze,
                'change_time':users.change_time,
                'delete':users.delete,
            },
        })

    @check_login
    def put(self,request):
        username = request.data.get("r_name")
        img = request.data.get("portrait")
        id = request.uid

        try:
            RiderModel.objects.filter(id=id).update(r_name=username,img=img)
        except Exception as e:
            print(e)
        return Response({
            "code":200,
            "msg":"修改用户信息成功"
        })


# 骑手的实名认证
class AutonymView(APIView):
    # 获取需要审核的信息
    def get(self,request):

        currentPage = request.query_params.get('page')
        pageSize = request.query_params.get('page_size')

        rider = RiderModel.objects.filter(is_audit=0)

        # 分页数据
        paginator = Paginator(rider, pageSize)
        # 获取当前页面  currentPage：页码
        page = paginator.page(currentPage)

        # 获取当前页面中的数据(商品对象) object_list:查询集
        data = page.object_list

        rider_list = []
        for i in data:
            rider_list.append({
                'id':i.id,
                'r_name':i.r_name,
                'mobile':i.mobile,
                'img':i.img,
                'login_time':i.login_time,
                'gender':i.gender,
                'reg_time':i.reg_time,
                'intro':i.intro,
                'real_name':i.real_name,
                'status':i.status,
                'hand_identity':i.hand_identity,
                'identity_front':i.identity_front,
                'identity_reverse':i.identity_reverse,
                'is_audit':i.is_audit,
                'balance':i.balance,
                'freeze':i.freeze,
                'change_time':datetime.strftime(i.change_time,'%Y-%m-%d %M:%H:%S'),
                'delete':i.delete,
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':rider_list,
            'total':len(rider),
        })
    @check_login
    def post(self,request):
        # 接受前端数据
        real_name = request.data.get('real_name')
        status = request.data.get('status')
        hand_identity = request.data.get('hand_identity')
        identity_front = request.data.get('identity_front')
        identity_reverse = request.data.get('identity_reverse')

        if not all([real_name,status,hand_identity,identity_front,identity_reverse]):
            return Response({
                'code':400,
                'msg':'接受的数据为空'
            })
        u_id = request.uid
        try:
            rider = RiderModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        rider.real_name = real_name
        rider.status = status
        rider.identity_reverse = identity_reverse
        rider.hand_identity = hand_identity
        rider.identity_front = identity_front
        rider.is_audit = 0
        rider.change_time = datetime.now()
        rider.save()

        return Response({
            'code':200,
            'msg':'等待审核'
        })

# 获取单个待审核骑手实名信息
class AutonymInfoView(APIView):
    def get(self,request,id):
        try:
            rider = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        return Response({
            'code':200,
            'msg':'获取成功',
            'data':{
                'id': rider.id,
                'r_name': rider.r_name,
                'mobile': rider.mobile,
                'img': rider.img,
                'login_time': rider.login_time,
                'gender': rider.gender,
                'reg_time': rider.reg_time,
                'intro': rider.intro,
                'real_name': rider.real_name,
                'status': rider.status,
                'hand_identity': rider.hand_identity,
                'identity_front': rider.identity_front,
                'identity_reverse': rider.identity_reverse,
                'is_audit': rider.is_audit,
                'balance': rider.balance,
                'freeze': rider.freeze,
                'change_time': datetime.strftime(rider.change_time, '%Y-%m-%d %M:%H:%S'),
                'delete': rider.delete,
            }
        })

    def put(self,request,id):
        try:
            rider = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        rider.is_audit = 1
        rider.save()

        return Response({
            'code':200,
            'msg':'审核成功'
        })

    # 进行驳回
    def delete(self,request,id):
        cause = request.query_params.get('cause')
        try:
            rider = RiderModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':'获取失败'
            })

        rider.is_audit = 2
        rider.cause_down = cause
        rider.save()

        return Response({
            'code':200,
            'msg':'驳回成功'
        })


# 今日流水 今日接单  用户余额
class RunningView(APIView):
    @check_login
    def get(self,request):
        u_id = request.uid

        rider = RiderOrderModel.objects.filter(rider_id=u_id)
        # 用户
        try:
            balance = RiderModel.objects.get(id=u_id)
        except Exception as e:
            return Response({
                'code':400,
                'msg':"没有此用户"
            })

        # 流水
        running = 0
        # 接单
        count_jie = 0
        for i in rider:
            if datetime.strftime(i.establish_time,'%Y-%m-%d') == datetime.strftime(datetime.now(),'%Y-%m-%d'):
                running += 10
                count_jie += 1

        return Response({
            'code':200,
            'msg':'获取成功',
            'running':running,
            'count_jie':count_jie,
            'balance':balance.balance,
        })





